/**
 * @author thaodo
 *
 *
 */
package com.mfsoft.fragment;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.content.res.Resources;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.support.v4.app.Fragment;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.mfsoft.adapter.GridViewAdapter;
import com.mfsoft.camera.R;
import com.mfsoft.model.ImageItem;
import com.mfsoft.utilities.Utils;
import com.mfsoft.utilities.Variables;

public class MyAlbumFragment extends Fragment implements OnItemClickListener {
	private GridView gvAlbum;
	private GridViewAdapter adapter;
	private int columnWidth;
	private Utils utils;
	private TextView tvNoImage;
	private ProgressBar pbgLoadMore;
	// my album
	File file;
	private File[] imageFiles;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View v = inflater.inflate(R.layout.grid_view, container, false);
		utils = new Utils(getActivity());

		gvAlbum = (GridView) v.findViewById(R.id.gvAlbum);
		tvNoImage = (TextView) v.findViewById(R.id.tvNoImage);
		pbgLoadMore = (ProgressBar) v.findViewById(R.id.pgbLoadMore);
		
		
		initGridLayout();
		adapter = new GridViewAdapter(getActivity(), R.drawable.loader,
				Variables.myAlbum,columnWidth);

		if (Variables.myAlbum.size() == 0) {
			// chua co anh, do chon mo anh tu server roi chuyen sang tab nay
			// load anh
			openMyAlbum();
		}

		if (Variables.myAlbum.size() == 0) {
			// chua co anh nao trong thu muc
			tvNoImage.setVisibility(View.VISIBLE);
		}

		gvAlbum.setAdapter(adapter);
		gvAlbum.setOnItemClickListener(this);

		return v;
	}

	public void initGridLayout() {
		Resources r = getResources();
		float padding = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
				Variables.GRID_PADDING, r.getDisplayMetrics());

		int diaInch = utils.diaInch();
		if (diaInch < 9 && diaInch >= 6.5) {
			// tablet 7: 3 hinh
			padding *= 2;
			columnWidth = (int) (utils.getScreenWidth() - ((Variables.NUM_OF_COLUMNS + 2) * padding)
					/ Variables.NUM_OF_COLUMNS);
		} else if (diaInch > 9) {
			// tablet 10
			padding *= 2;
			columnWidth = (int) (utils.getScreenWidth() - ((Variables.NUM_OF_COLUMNS + 2) * padding)
					/ Variables.NUM_OF_COLUMNS);
		} else {
			// fix chieu rong cua hinh
			columnWidth = (int) (utils.getScreenWidth() - ((Variables.NUM_OF_COLUMNS + 1) * padding)
					/ Variables.NUM_OF_COLUMNS);
			gvAlbum.setNumColumns(Variables.NUM_OF_COLUMNS);

		}
		
		gvAlbum.setColumnWidth(columnWidth);
//		gvAlbum.setStretchMode(GridView.NO_STRETCH);
		gvAlbum.setPadding((int) padding, (int) padding, (int) padding,
				(int) padding);
		gvAlbum.setHorizontalSpacing((int) padding);
		gvAlbum.setVerticalSpacing((int) padding);
	}
	
	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int position,
			long arg3) {
		// click vao moi hinh anh thi ....
		Intent intent = getActivity().getIntent();
		// put object image item tuong ung di
		intent.putExtra("image", Variables.myAlbum.get(position));
		// System.out.println("anh: " +
		// Variables.myAlbum.get(position).toString());
		// startActivity(intent);
		getActivity().setResult(Activity.RESULT_OK, intent);
		getActivity().finish();
	}

	// mo Album
	public ArrayList<ImageItem> openMyAlbum() {
		Variables.myAlbum.clear();
		// kiem tra sdcard
		if (!Environment.getExternalStorageState().equals(
				Environment.MEDIA_MOUNTED)) {
			Toast.makeText(getActivity(), "Khong tim thay sdcart",
					Toast.LENGTH_LONG).show();
		} else {
			file = new File(Environment.getExternalStorageDirectory()
					+ File.separator + "myalbumcamera");
			// mo thu muc mac dinh cua myalbum
			// neu ko co thi tao moi
			if (!file.exists()) {
				file.mkdirs();
			}
		}

		// new OpenMyAlbumTask().execute();
		// Toast.makeText(this, "album: " + Variables.myAlbum.size(),
		// Toast.LENGTH_LONG).show();
		new LoadMoreAlbumTask().execute();
		return Variables.myAlbum;
	}

	@SuppressLint("SimpleDateFormat")
	class LoadMoreAlbumTask extends AsyncTask<Void, Void, Void> {

		@Override
		protected Void doInBackground(Void... params) {

			if (file.isDirectory()) {
				imageFiles = file.listFiles();
				// ko nen, cho vao string, tieng viet thi value-vn, tieng anh
				// value-en
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
				for (int i = 0; i < imageFiles.length; i++) {
					Variables.myAlbum.add(new ImageItem("", imageFiles[i]
							.getName(), imageFiles[i].length() / 1024 + "kb",
							sdf.format(imageFiles[i].lastModified()),
							imageFiles[i].getAbsolutePath()));
				}
				// System.out.println("album: " + Variables.myAlbum.size());
			}
			return null;
		}

		@Override
		protected void onPostExecute(Void result) {
			pbgLoadMore.setVisibility(View.GONE);
			super.onPostExecute(result);
		}

		@Override
		protected void onPreExecute() {
			pbgLoadMore.setVisibility(View.VISIBLE);
			super.onPreExecute();
		}
	}

}
